package com.zjy.financialsystemjavafx.controller;

import com.zjy.financialsystemjavafx.model.entity.Transaction;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import java.io.IOException;
import java.time.LocalDate;
import com.zjy.financialsystemjavafx.service.DashboardService;
import com.zjy.financialsystemjavafx.service.TransactionService;
import com.zjy.financialsystemjavafx.util.SessionContext;
import java.time.YearMonth;
import java.util.Map;

/**
 * 报表统计控制器
 */
public class ReportController {

    @FXML
    private LineChart<String, Number> monthlySummaryChart;

    @FXML
    private BarChart<String, Number> categoryBarChart;

    @FXML
    private TableView<Transaction> reportTable;

    @FXML
    private TableColumn<Transaction, Integer> reportIdColumn;

    @FXML
    private TableColumn<Transaction, String> reportTypeColumn;

    @FXML
    private TableColumn<Transaction, Double> reportAmountColumn;

    @FXML
    private TableColumn<Transaction, LocalDate> reportDateColumn;

    @FXML
    private TableColumn<Transaction, String> reportAccountColumn;

    @FXML
    private TableColumn<Transaction, String> reportCategoryColumn;

    @FXML
    private TableColumn<Transaction, String> reportDescColumn;

    @FXML
    private Button backButton;

    private ObservableList<Transaction> reportData = FXCollections.observableArrayList();

    @FXML
    private void initialize() {
        int userId = SessionContext.getCurrentUser().getUserId();
        DashboardService ds = new DashboardService();
        TransactionService ts = new TransactionService();

        // 月度汇总（近12月）
        YearMonth end = YearMonth.now();
        YearMonth start = end.minusMonths(11);
        try {
            Map<YearMonth, Double> incMap = ds.getMonthlyAmount(userId, start, end, "Income");
            Map<YearMonth, Double> expMap = ds.getMonthlyAmount(userId, start, end, "Expense");
            XYChart.Series<String, Number> incSeries = new XYChart.Series<>();
            incSeries.setName("收入");
            XYChart.Series<String, Number> expSeries = new XYChart.Series<>();
            expSeries.setName("支出");
            for (YearMonth ym : incMap.keySet()) {
                String label = String.format("%02d月", ym.getMonthValue());
                incSeries.getData().add(new XYChart.Data<>(label, incMap.get(ym)));
                expSeries.getData().add(new XYChart.Data<>(label, expMap.get(ym)));
            }
            monthlySummaryChart.getData().clear();
            monthlySummaryChart.getData().addAll(incSeries, expSeries);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 分类报表（支出）
        try {
            Map<String, Double> catMap = ds.getExpenseByCategory(userId);
            XYChart.Series<String, Number> catSeries = new XYChart.Series<>();
            catSeries.setName("支出分类");
            for (Map.Entry<String, Double> entry : catMap.entrySet()) {
                catSeries.getData().add(new XYChart.Data<>(entry.getKey(), entry.getValue()));
            }
            categoryBarChart.getData().clear();
            categoryBarChart.getData().add(catSeries);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 账户流水表格
        reportIdColumn.setCellValueFactory(new PropertyValueFactory<>("transactionId"));
        reportTypeColumn.setCellValueFactory(new PropertyValueFactory<>("transactionType"));
        reportAmountColumn.setCellValueFactory(new PropertyValueFactory<>("amount"));
        reportDateColumn.setCellValueFactory(new PropertyValueFactory<>("transactionDate"));
        reportAccountColumn.setCellValueFactory(new PropertyValueFactory<>("accountName"));
        reportCategoryColumn.setCellValueFactory(new PropertyValueFactory<>("categoryName"));
        reportDescColumn.setCellValueFactory(new PropertyValueFactory<>("description"));
        reportTable.setItems(reportData);
        try {
            reportData.clear();
            reportData.addAll(ts.getTransactions(userId));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回仪表盘视图
     */
    @FXML
    private void handleBack(ActionEvent event) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/Dashboard.fxml"));
            Stage stage = (Stage) backButton.getScene().getWindow();
            stage.setTitle("个人财务管家 - 仪表盘");
            stage.setScene(new Scene(root));
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载仪表盘界面");
            alert.showAndWait();
        }
    }
} 